package com.ckerchina.admin.ckadmin.service.wx.messagehandler.eventhandler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.ckerchina.admin.ckadmin.dao.WxUserDAO;
import com.ckerchina.admin.ckadmin.domain.WXUser;
import com.ckerchina.admin.ckadmin.service.WxPublicService;
import com.ckerchina.admin.ckadmin.service.wx.WxEventMessage;
import com.ckerchina.admin.ckadmin.service.wx.WxMessage;
import com.ckerchina.admin.ckadmin.service.wx.messagehandler.WxEventHandler;

import java.io.IOException;
import java.util.Date;

/**
 * Created by 晓丰 on 2016/2/12.
 */
@Component
public class SubscribeEventHandler implements WxEventHandler {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());


    @Autowired
    WxPublicService wxService;

    @Autowired
    WxUserDAO wxUserDAO;


    @Transactional
    public WxMessage handleEvent(WxEventMessage eventMessage) throws IOException {

        String userid = eventMessage.getEventKey();
        String fromUserName = eventMessage.getFromUserName();
        WXUser wxUserByOpenid = wxService.getWxUserByOpenid(fromUserName);
        WXUser wxUser = wxUserDAO.find(wxUserByOpenid.getUnionid());
        if(wxUser==null){
            if(!StringUtils.isEmpty(userid)){
                String[] split = userid.split("_");
                wxUserByOpenid.setParentUserid(new Long(split[1]));
            }
            wxUserDAO.persist(wxUserByOpenid);
        }else{
            if(!StringUtils.isEmpty(userid)){
                wxUser.setParentUserid(new Long(userid));
            }
            wxUser.setOpenid(fromUserName);
            wxUserDAO.merge(wxUser);
        }
        WxMessage wxMessage = new WxMessage();
        wxMessage.setContent("欢迎关注诸子");
        wxMessage.setMsgType("text");
        wxMessage.setCreateTime(new Date());
        wxMessage.setFromUserName(eventMessage.getToUserName());
        wxMessage.setToUserName(eventMessage.getFromUserName());
        return wxMessage;
    }

    @Override
    public String getEvent() {
        return "subscribe";
    }
}
